<?php

namespace App\Http\Controllers;

use App\Models\GrAddress;
use App\Models\GrCity;
use App\Models\GrGood;
use App\Models\GrUser;
use App\Models\OrderGoods;
use App\Models\StoreCombination;
use App\Models\StorePink;
use App\service\JwtService;
use App\service\ReturnService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use function Qiniu\thumbnail;

class GroupBooking extends Controller
{

    private $redis;

    public function __construct()
    {
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);
    }

    //商品预热

    /**
     *  $count 库存数量
     *  $groupId 拼团id
     *  $groupNumber 成团人数
     *  $startTime 活动开始时间
     *  $endTime 活动结束时间
     *  $effectiveTime 时效
     *  $userRestrictions
     */
    public function preheat($count, $groupId, $groupNumber, $startTime, $endTime, $effectiveTime, $userRestrictions)
    {
        $endTime = strtotime($endTime);
        $startTime = strtotime($startTime);
        for ($i = 1; $i <= $count; $i++) {
            $this->redis->lPush('groupList_' . $groupId, 1);
        }
        $this->redis->expire('groupList_' . $groupId, $endTime - time());
        $this->redis->set('groupNumber_' . $groupId, $groupNumber, $endTime - time());
        $this->redis->set('groupStart_' . $groupId, $startTime, $endTime - time());
        $this->redis->set('effectiveTime_' . $groupId, $effectiveTime, $endTime - time());
        $this->redis->set('user_group_' . $groupId, $userRestrictions, $endTime - time());
    }

    public function groupList()
    {
        $data = StorePink::where('status', 1)->paginate(3);
        if (empty($data)) {
            return ReturnService::failedReturn( '暂无拼团');
        }
        return ReturnService::successReturn( '查询成功', $data);
    }

    //商品上架列表
    public function show()
    {
        $data = GrGood::where('status', 1)->paginate(6);
        return ReturnService::successReturn( '查询成功', $data);
    }

    //商品详情
    public function goodsDetails(Request $request)
    {
        $id = $request->get('id');
        $res = GrGood::where('goods_id', $id)->first();
        $res['goods_img'] = json_decode($res['goods_img']);
        return ReturnService::successReturn( '查询成功', $res);
    }

    //获取用户收获地址
    public function getAddress(Request $request)
    {
        $token = $request->get('token');
        $userId = JwtService::decodeToken($token);
        $id = $userId->data->id;
        $data = GrAddress::where('uid', $id)->get()->toArray();
        return ReturnService::successReturn( '查询成功', $data);

    }

    //查询城市三级联动
    public function getCity(Request $request)
    {
        $provinces = $request->get('provinces');
        $cityId = $request->get('city_id');
        if ($provinces == 0) {   //0为省
            $res = GrCity::where('parent_id', 0)->get();
            return ReturnService::successReturn( '查询成功', $res);
        }
        if ($provinces == 1 || $provinces == 2) {
            $res = GrCity::where('parent_id', $cityId)->get();
            return ReturnService::successReturn( '查询成功', $res);
        }
    }

    //添加地址
    public function addAddress(Request $request)
    {
        $token = $request->post('token');
        $realName = $request->post('real_name');
        $phone = $request->post('phone');
        $detail = $request->post('detail');
        $cityId = $request->post('city_id');
        $userId = JwtService::decodeToken($token);
        $uid = $userId->data->id;
        $city = GrCity::where('city_id', $cityId)->first()->toArray();
        $info = GrAddress::where('uid', $uid)->get()->toArray();
        //判断是否已有收货地址
        if (empty($info)) {
            $default = 1; //1默认
        } else {
            $default = 0; //不默认
        }
        $data = [
            'uid' => $uid,
            'real_name' => $realName,
            'phone' => $phone,
            'detail' => $detail,
            'city_id' => $cityId,
            'longitude' => $city['lng'],
            'latitude' => $city['lat'],
            'is_default' => $default,
        ];
        $res = GrAddress::create($data);
        return ReturnService::successReturn( '添加成功', $res);
    }

    //收获地址修改默认
    public function addressDefault(Request $request)
    {
        $ids = $request->post('ids');
        $token = $request->post('token');
        $userId = JwtService::decodeToken($token);
        $uid = $userId->data->id;
        $data = GrAddress::where('uid', $uid)->where('is_default', 1)->first();
        $res = GrAddress::where('id', $ids)->where('uid', $uid)->first();
        // 启动事务
        DB::beginTransaction();
        try {
            $data->update(['is_default' => 0]);
            $res->update(['is_default' => 1]);
            // 提交事务
            DB::commit();
            return ReturnService::successReturn( '设置成功', $res);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return ReturnService::failedReturn( '设置失败');
        }
    }

    //删除地址
    public function delAddress(Request $request)
    {
        $ids = $request->get('ids');
        $token = $request->get('token');
        $user_id = JwtService::decodeToken($token);
        $uid = $user_id->data->id;
        $data = GrAddress::where('uid', $uid)->where('id', $ids)->delete();
        return ReturnService::successReturn( '删除成功', []);
    }

    //拼团商品展示
    public function groupGoods()
    {
        $data = StoreCombination::where('is_show', 1)->paginate(3);
        return ReturnService::successReturn( '查询成功', $data);
    }

    //发起拼团
    public function beganGroup(Request $request)
    {
        $groupId = $request->post('group_id');  //拼团活动id
        $token = $request->post('token');
        $userId = JwtService::decodeToken($token);
        $uid = $userId->data->id;
        $user = GrUser::where('id', $uid)->first()->toArray();
//        dd($user);
        if ($user['is_colonel'] == 0) {
            return ReturnService::failedReturn('只有团长才能发起拼团');
        }
        $startTime = $this->redis->get('groupStart_' . $groupId);
        if (!$startTime) {
            return ReturnService::failedReturn( '该商品活动还未开始');
        }
        $goodInfo = 'groupList_' . $groupId;
        // lLen 命令用于返回列表的长度
        $goodsList = $this->redis->lLen($goodInfo);
        if ($goodsList < 1) {
            return ReturnService::failedReturn('商品已被拼完');
        }
        $effectiveTime = $this->redis->get('effectiveTime_' . $groupId);
        $totalTime = time() + 60 * 60 * $effectiveTime;
        $endTime = date('Y-m-d h:i:s', $totalTime);

        $num = $this->redis->get('groupNumber_' . $groupId);
        $goods = StoreCombination::where('id', $groupId)->first()->toArray();

        // 启动事务
        Db::beginTransaction();
        try {
            //  Redis Watch 命令用于监视一个(或多个) key ，如果在事务执行之前这个(或这些) key 被其他命令所改动，那么事务将被打断
            $this->redis->watch(array($goodInfo));
            $this->redis->multi();
            for ($i = 1; $i <= $num; $i++) {
                $this->redis->rPop($goodInfo);
            }
            //Redis Exec 命令用于执行所有事务块内的命令
            $this->redis->exec();
            $data = [
                'uid' => $uid,
                'nickname' => $user['username'],
                'avatar' => $user['head_portrait'],
                'cid' => $groupId,
                'add_time' => date('Y-m-d h:i:s', $startTime),
                'stop_time' => $endTime,
                'k_id' => $user['is_colonel'],
                'price' => $goods['price'],
                'status' => 1,
            ];
            StorePink::create($data);
            // 提交事务
            Db::commit();
            return ReturnService::successReturn( '发起拼团成功', []);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ReturnService::failedReturn( '发起拼团失败');
        }
    }

    //加入拼团
    public function groupAdd(Request $request)
    {
        $kId = $request->post('k_id'); //团长id
        $groupId = $request->post('group_id'); //拼团商品活动id
        $regiment = $request->post('regiment_id'); // 该团id
        $addressId = $request->post('address_id');
        $token = $request->post('token');
        $userId = JwtService::decodeToken($token);
        $uid = $userId->data->id;       // 用户id
        $userCredentials = 'user_credentials_' . $groupId;    //用户凭证
        $groupNumber = 'group_' . $uid . $groupId;  //团人数凭证
        $userGroup = 'user_groupId_' . $regiment; //用户在本团凭证


        $store = StorePink::where('id', $regiment)->first()->toArray();
//        dd($store);
//        $state = StorePink::where('status', $regiment)->first();
        if ($store['status'] != 1) {
            return ReturnService::failedReturn( '该团已结束');
        }
        // Sismember 命令判断成员元素是否是集合的成员。如果成员元素是集合的成员，返回 1 。 如果成员元素不是集合的成员，或 key 不存在，返回 0 。
        $existsUser = $this->redis->sIsMember($userGroup, $uid);
        if ($existsUser) {
            return ReturnService::failedReturn( '你已在拼团中');
        }
        $count = $this->redis->zScore($userCredentials, $groupId);
//        dd($count);
        if ($count >= $this->redis->get('user_group_' . $groupId)) {
            return ReturnService::failedReturn( '你已购买最大量了');
        }
        $groupPeople = $this->redis->zScore($groupNumber, $groupId); //团人数

        $goodsNumber = $this->redis->get('groupNumber_' . $groupId); //该商品成团人数

        if ($groupPeople >= $goodsNumber) {
            return ReturnService::failedReturn( '拼团人数已满');
        }
        $goods = StorePink::where('cid', $groupId)->first()->toArray();
//        $goodsInfo = StoreCombination::where('id', $groupId)->first()->toArray();
//        dd($goods);
//        dd($goodsInfo);
        // 启动事务
        Db::beginTransaction();
        try {
            //雪花算法
            $snowflake = new \Godruoyi\Snowflake\Snowflake;
            $data = [
                'order_sn' => $snowflake->id(),
                'user_id' => $uid,
                'goods_money' => $goods['price']*$count,
                'is_pay' => 0,
                'address_id' => $addressId,
            ];

            \App\Models\Order::create($data);
//            $order = Order::where('order_sn', $data['order_sn'])->first();
//            dd($data['order_sn']);
            $order=\App\Models\Order::where('order_sn',$data['order_sn'])->first()->toArray();
//            dd($order);
//            dd($data,$data['order_sn']);
            $info = [
                'order_id' => $order['id'],
                'goods_id' => $goods['cid'],
                'goods_number' => $goods['total_num'],
            ];
            OrderGoods::create($info);
            $this->redis->watch(array($userCredentials, $goodsNumber));
            $this->redis->multi();
            //Redis Zincrby 命令对有序集合中指定成员的分数加上增量 increment
            $this->redis->zIncrBy($userCredentials, 1, $uid);
            $groupCount = $this->redis->zIncrBy($groupNumber, 1, $groupId);
            //Redis Sadd 命令将一个或多个成员元素加入到集合中，已经存在于集合的成员元素将被忽略。
            $this->redis->sAdd($userGroup, $uid);
            if ($groupCount >= $goodsNumber) {
                StorePink::where('k_id', $kId)->update(['status' => 2]);
//                StoreCombination::where('id',$groupId)->update(['']);
            }
            // 提交事务
            Db::commit();
            return ReturnService::successReturn( '加入拼团成功', []);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ReturnService::failedReturn('加入拼团失败');
        }


    }






//    public function pay(Request $request)
//    {
//        $param = $request->post();
////        dd($param['goods_id']);
//        $goods_id = $param['goods_id'];
//        $arr = [];
//        foreach ($goods_id as $k => $v) {
////            $goods = GoodsList::where('id',$goods_id)->orwhere('id',$v)->with('unit')->get()->toArray();
//            $goods = GoodsList::where('id', $v)->with('unit')->get()->toArray();
//            $arr[$k] = $goods;
//        }
////        dd($arr);
//
//
//        $totalMoney = $goods['goods_price'] * $param['quantity'];
//        $coupon = CouponGet::where('coupon_id', $param['coupon_id'])->first();
////        dd($coupon->toArray());
//        $token = $request->post('token');
//
//        $user_id = JwtService::getDecoded($token);
//        $user_id = $user_id['id'];
//
//        $address = Address::where('user_id', $user_id)->get();
////            dd($address->toArray());
//        $address_id = $address->where('id', $param['address_id'])->first()->toArray();
//
//
//        //雪花算法
//        $snowflake = new \Godruoyi\Snowflake\Snowflake;
////
////        $snowflake->id();
////        dd($snowflake->id());
//
//        if ($param['quantity'] > $goods['goods_stock']) {
//            return ['code' => 300, 'msg' => '库存不足', 'data' => ''];
//        }
//
//        // 启动事务
//        DB::beginTransaction();
//        try {
//            $data = [
//                'order_sn' => $snowflake->id(),
//                'user_id' => $user_id,
//                'order_status' => 0,
//                'consignee' => $address_id['name'],
//                'address' => $address_id['detailed_address'],
//                'phone' => $address_id['mobile'],
//                'pay_time' => null,
//                'total_amount' => $param['total_money'],
//                'order_amount' => $param['actuallyPaid'],
//                'postage' => $param['postage'],
//                'user_note' => $param['remarks'],
//                'coupon_price' => $param['coupon_price'],
//                'pay_name' => '',
//            ];
//
//            Order::create($data);
//            $order = Order::where('order_sn', $data['order_sn'])->first();
////            dd($order['id']);
//            $info = [
//                'number' => $param['quantity'],
//                'order_sn' => $order['id'],
//                'goods_id' => $param['goods_id'],
//                'goods_name' => $goods['goods_name'],
//                'goods_price' => $goods['goods_price'],
//            ];
//            OrderGood::create($info);
//
//            $goods['goods_stock'] = $goods['goods_stock'] - $param['quantity'];
//            GoodsList::where('id', $param['goods_id'])->update(['goods_stock' => $goods['goods_stock']]);
//            $coupon->update(['status' => 1]);
//            // 提交事务
//            DB::commit();
//            return ['code' => 200, 'msg' => '下单成功', 'data' => $data];
//        } catch (\Exception $e) {
//            // 回滚事务
//            DB::rollback();
//            return ['code' => 300, 'msg' => '下单失败', 'data' => []];
//        }
//    }

    public function pay(Request $request){
        $token = $request->post('token');
        $userId = JwtService::decodeToken($token);
        $uid = $userId->data->id;       // 用户id
    }
}
